import json
import random

import requests
from bs4 import BeautifulSoup
from django.http import JsonResponse
from py2neo import *
from django.shortcuts import render, redirect
from utils.ans.chatbot_graph import ChatBotGraph

# 连接数据库
graph = Graph('neo4j://localhost:7687', auth=('neo4j', '12345678'))


def search_all():
    # 定义data数组，存放节点信息
    data = []
    # 定义关系数组，存放节点间的关系
    links = []
    # 定义tabledata数组，存放列表要展示的数据
    tabledata = []
    # 查询所有节点，并将节点信息取出存放在data数组中
    # 执行Cypher查询

    query = 'MATCH (n:`公司`) RETURN n limit 250'
    result = graph.run(query)
    for n in result:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        node_code = nodesList[0]['股票代码']
        table_dict = {
            'code': node_code,
            'name': node_name,
            'label': '公司',
        }
        tabledata.append(table_dict)

    query = "MATCH (n:`股票`) RETURN n limit 250"
    result = graph.run(query)
    for n in result:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        node_code = nodesList[0]['代码']
        table_dict = {
            'code': node_code,
            'name': node_name,
            'label': '股票'
        }
        tabledata.append(table_dict)

    query = "MATCH  ()-[rel:`属于`]->(m:行业) RETURN rel LIMIT 50"
    result = graph.run(query).data()

    # print(result)
    for r in result:
        source = str(r['rel'].start_node['名称'])
        source_other_attributes = r['rel'].start_node
        target = str(r['rel'].end_node['名称'])
        target_other_attributes = r['rel'].end_node
        name = str(type(r['rel']).__name__)
        dict = {
            'source': source,
            'target': target,
            'name': name
        }
        source_dict = {
            'name': source,
            'symbolSize': 50,
            'category': '公司',
            'des': source_other_attributes
        }
        target_dict = {
            'name': target,
            'symbolSize': 50,
            'category': '行业',
            'des': target_other_attributes
        }
        if source_dict not in data:
            data.append(source_dict)
        if target_dict not in data:
            data.append(target_dict)
        # 将单个关系信息存放进links数组中
        links.append(dict)
    neo4j_data = {
        'data': data,
        'links': links
    }
    neo4j_data = json.dumps(neo4j_data)
    return neo4j_data, tabledata


def search_one(value):
    # 定义data数组存储节点信息
    data = []
    # 定义links数组存储关系信息
    links = []
    # 查询节点是否存在
    node = graph.run('MATCH(n{名称:"' + value + '"}) return n')
    list = node.data()
    # 如果节点存在len(node)的值为1不存在的话len(node)的值为0
    if len(list):
        # 如果该节点存在将该节点存入data数组中
        # 构造字典存放节点信息
        labels = node[0].labels
        label = next(iter(labels))
        label = label.replace(':', '')
        other_attributes = list[0]['n']
        dict = {
            'name': value,
            'symbolSize': 50,
            'category': label,
            'des': other_attributes
        }
        data.append(dict)
        # 查询与该节点有关的节点，无向，步长为1，并返回这些节点
        nodes = graph.run('MATCH (n{名称:"' + value + '"}) -[r]- (m) RETURN distinct m')
        # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
        reps = graph.run('MATCH(n{名称:"' + value + '"})-[rel]-() return rel').data()
        # 处理节点信息
        for n in nodes:
            # 将节点信息的格式转化为json
            node = json.dumps(n.data(), ensure_ascii=False)
            node = json.loads(node)
            # 取出节点信息中person的name
            name = str(node['m']['名称'])
            other_attributes = node['m']
            labels = n[0].labels
            label = next(iter(labels))
            label = label.replace(':', '')

            # 构造字典存放单个节点信息
            dict = {
                'name': name,
                'symbolSize': 50,
                'category': label,
                'des': other_attributes
            }
            # 将单个节点信息存储进data数组中
            data.append(dict)
        # 处理relationship
        for r in reps:
            source = str(r['rel'].start_node['名称'])
            target = str(r['rel'].end_node['名称'])
            name = str(type(r['rel']).__name__)
            des = ''
            if name == '任职':
                des = r['rel']['职位']
            elif name == '属于':
                des = r['rel']['级别']
            elif name == '成分':
                des = r['rel']['排名']
            elif name == '投资':
                des = r['rel']['占总股本比例']

            dict = {
                'source': source,
                'target': target,
                'name': name,
                'des': des
            }
            links.append(dict)
        # 构造字典存储data和links
        search_neo4j_data = {
            'data': data,
            'links': links
        }
        # 将dict转化为json格式
        search_neo4j_data = json.dumps(search_neo4j_data)
        return search_neo4j_data
    else:
        print("查无实体")
        return 0


def index(request):
    ctx = {}
    search_neo4j_data = {}
    flag = {}
    if request.method == 'POST':
        # 接收前端传过来的查询值
        node_name = request.POST.get('node')
        if node_name == "":
            flag = {'title': '传值为空'}
        # 查询结果
        if flag:
            print(flag)
        search_neo4j_data = search_one(node_name)
        # 未查询到该节点
        if search_neo4j_data == 0:
            ctx = {'title': '数据库中暂未添加该实体'}
            neo4j_data, table_data = search_all()
            return render(request, 'index_.html',
                          {'neo4j_data': neo4j_data, 'ctx': ctx, 'table_data': table_data, 'flag': flag})
        # 查询到了该节点
        else:
            request.session['search_neo4j_data'] = search_neo4j_data
            # 将 ctx 数据放入会话中，根据实际情况进行处理
            request.session['ctx'] = ctx
            request.session['flag'] = flag
            # return redirect('query_')
            neo4j_data, table_data = search_all()
            return render(request, 'index_.html',
                          {'neo4j_data': neo4j_data, 'search_neo4j_data': search_neo4j_data, 'ctx': ctx, 'flag': flag,
                           'table_data': table_data})

    else:
        search_neo4j_data = request.session.pop('search_neo4j_data', None)
        ctx = request.session.pop('ctx', None)
        flag = request.session.pop('flag', None)

    neo4j_data, table_data = search_all()
    return render(request, 'index_.html', {'neo4j_data': neo4j_data, 'ctx': ctx, 'flag': flag, 'table_data': table_data,
                                           'search_neo4j_data': search_neo4j_data})


def qa_chat_view(request):
    return render(request, 'qachat.html')


def get_response(request):
    body = json.loads(request.body.decode('utf-8'))
    # 这里调用模型或API来获取问题的回答
    print(body['question'])
    handler = ChatBotGraph()
    answer = handler.chat_kg_main(body['question'])
    print(answer)
    return JsonResponse({'response': answer})


def qa_chat_view(request):
    return render(request, 'qachat.html')


def stock(request):
    tabledata = []
    stock_rank_data = []
    query = 'MATCH (n:`股票`) RETURN n'
    result = graph.run(query)
    for n in result:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        node_code = nodesList[0]['代码']
        # 构造字典，存储单个节点信息
        dict = {
            'code': node_code,
            'name': node_name,
        }
        tabledata.append(dict)
    reps = graph.run('MATCH(n:`股票`) -[rel:`成分`]- (m:`指数`) return rel LIMIT 100').data()
    for r in reps:
        source = str(r['rel'].start_node['名称'])
        des = int(r['rel']['排名'])
        dict = {
            'stock': source,
            'rank': des
        }
        stock_rank_data.append(dict)
    stock_rank_data = json.dumps(stock_rank_data)
    return render(request, 'stock.html', {'tabledata': tabledata, 'stock_rank_data': stock_rank_data})


def industry(request):
    ctx = {}
    industry_neo4j_data = 0
    industry_data = []
    indus_node = graph.run('MATCH(n:`行业`) return n')
    for n in indus_node:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        des = nodesList[0]['级别']
        dict = {
            'name': node_name,
            'level': des
        }
        industry_data.append(dict)

    if request.method == "POST":
        node_name = request.POST.get('industry_node')
        # 定义data数组存储节点信息
        data = []
        # 定义links数组存储关系信息
        links = []
        # 查询节点是否存在
        node = graph.run('MATCH(n:`行业`{名称:"' + node_name + '"}) return distinct n').data()
        # 如果节点存在len(node)的值为1不存在的话len(node)的值为0
        if len(node):
            # 如果该节点存在将该节点存入data数组中
            # 构造字典存放节点信息
            other_attributes = node[0]['n']
            dict = {
                'name': node_name,
                'symbolSize': 50,
                'category': '行业',
                'des': other_attributes
            }
            data.append(dict)
            # 查询与该节点有关的节点，无向，步长为1，并返回这些节点
            nodes = graph.run('MATCH(n:`行业`{名称:"' + node_name + '"}) -[]-(m) return distinct m')
            # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
            reps = graph.run('MATCH(n:`行业`{名称:"' + node_name + '"}) -[rel]- (m) return rel').data()
            # 处理节点信息
            for n in nodes:
                # 将节点信息的格式转化为json
                node = json.dumps(n.data(), ensure_ascii=False)
                node = json.loads(node)
                # 取出节点信息中person的name
                name = str(node['m']['名称'])
                other_attributes = node['m']
                labels = n[0].labels
                label = next(iter(labels))
                label = label.replace(':', '')

                # 构造字典存放单个节点信息
                dict = {
                    'name': name,
                    'symbolSize': 50,
                    'category': label,
                    'des': other_attributes
                }
                # 将单个节点信息存储进data数组中
                data.append(dict)
            # 处理relationship
            for r in reps:
                source = str(r['rel'].start_node['名称'])
                target = str(r['rel'].end_node['名称'])
                name = str(type(r['rel']).__name__)
                dict = {
                    'source': source,
                    'target': target,
                    'name': name
                }
                links.append(dict)
            # 构造字典存储data和links
            search_data = {
                'data': data,
                'links': links
            }
            # 将dict转化为json格式
            industry_neo4j_data = json.dumps(search_data)
            request.session['industry_neo4j_data'] = industry_neo4j_data
            # 将 ctx 数据放入会话中，根据实际情况进行处理
            request.session['ctx'] = ctx
        else:
            ctx = {'title': '数据库中暂未添加该实体'}
            print("查无实体")
    else:
        industry_neo4j_data = request.session.pop('industry_neo4j_data', None)
        ctx = request.session.pop('ctx', None)
    return render(request, 'industry.html',
                  {'industry_neo4j_data': industry_neo4j_data, 'ctx': ctx, 'industry_data': industry_data})


def stock_index(request):
    ctx = {}
    index_neo4j_data = 0

    stock_index_data = []
    draw_data = []
    indus_node = graph.run('MATCH(n:`指数`) return n')
    for n in indus_node:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        stock_index_data.append(node_name)

    index_node = graph.run('MATCH(n:`指数`) return n LIMIT 25')
    for n in index_node:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        # 构造字典，存储单个节点信息
        node_range = float(nodesList[0]['涨跌幅(%)'])
        node_yes = float(nodesList[0]['昨收'])
        dict = {
            'yesterday': node_yes,
            'range': node_range,
            'name': node_name
        }
        draw_data.append(dict)
    draw_data = json.dumps(draw_data)

    if request.method == "POST":
        node_name = request.POST.get('index_node')
        # 定义data数组存储节点信息
        data = []
        # 定义links数组存储关系信息
        links = []
        # 查询节点是否存在
        node = graph.run('MATCH(n:`指数`{名称:"' + node_name + '"}) return n').data()
        # 如果节点存在len(node)的值为1不存在的话len(node)的值为0
        if len(node):
            # 如果该节点存在将该节点存入data数组中
            # 构造字典存放节点信息
            other_attributes = node[0]['n']
            dict = {
                'name': node_name,
                'symbolSize': 50,
                'category': '指数',
                'des': other_attributes
            }
            data.append(dict)
            # 查询与该节点有关的节点，无向，步长为1，并返回这些节点
            nodes = graph.run('MATCH(n:`指数`{名称:"' + node_name + '"}) -[]-(m:`股票`) return m')
            # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
            reps = graph.run('MATCH(n:`指数`{名称:"' + node_name + '"}) -[rel]- (m:`股票`) return rel').data()
            # 处理节点信息
            for n in nodes:
                # 将节点信息的格式转化为json
                # 将节点信息的格式转化为json
                node = json.dumps(n.data(), ensure_ascii=False)
                node = json.loads(node)
                # 取出节点信息中person的name
                name = str(node['m']['名称'])
                other_attributes = node['m']
                labels = n[0].labels
                label = next(iter(labels))
                label = label.replace(':', '')

                dict = {
                    'name': name,
                    'symbolSize': 50,
                    'category': '股票',
                    'des': other_attributes
                }
                # 将单个节点信息存储进data数组中
                data.append(dict)
            # 处理relationship
            for r in reps:
                source = str(r['rel'].start_node['名称'])
                target = str(r['rel'].end_node['名称'])
                name = str(type(r['rel']).__name__)
                dict = {
                    'source': source,
                    'target': target,
                    'name': name
                }
                links.append(dict)
            # 构造字典存储data和links
            search_data = {
                'data': data,
                'links': links
            }
            # 将dict转化为json格式
            index_neo4j_data = json.dumps(search_data)
            request.session['index_neo4j_data'] = index_neo4j_data
            # 将 ctx 数据放入会话中，根据实际情况进行处理
            request.session['ctx'] = ctx
        else:
            ctx = {'title': '数据库中暂未添加该实体'}
            print("查无实体")
    else:
        index_neo4j_data = request.session.pop('index_neo4j_data', None)
        ctx = request.session.pop('ctx', None)

    # 实时爬取函数
    user_agents = [
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
        "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
        "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
        "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
        "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
        "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
        "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
    ]

    request_headers = {
        "User-Agent": random.choice(user_agents),
    }
    url = 'http://q.10jqka.com.cn/zs/detail/code/399300/'
    response = requests.get(url, headers=request_headers)
    response.encoding = 'utf-8'
    if response.status_code == 200:
        html_content = response.text
        # 在这里对获取到的数据进行处理
        soup_doc = BeautifulSoup(html_content, "html.parser")
        price_pos = soup_doc.select(
            'body > div.container.w1200 > div:nth-child(3) > div.body > div > div > div.heading > div.board-hq > span')
        price = price_pos[0].text
    else:
        print('请求失败')

    return render(request, 'stock_index.html',
                  {'index_neo4j_data': index_neo4j_data, 'ctx': ctx, 'stock_index_data': stock_index_data,
                   'draw_data': draw_data})


def company(request):
    ctx = {}
    company_neo4j_data = 0
    company_data = []
    compy_node = graph.run('MATCH(n:`公司`) return n limit 100')
    for n in compy_node:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        company_data.append(node_name)

    if request.method == "POST":
        node_name = request.POST.get('company_node')
        # 定义data数组存储节点信息
        data = []
        # 定义links数组存储关系信息
        links = []
        # 查询节点是否存在
        node = graph.run('MATCH(n:`公司`{名称:"' + node_name + '"}) return n').data()
        # 如果节点存在len(node)的值为1不存在的话len(node)的值为0
        if len(node):
            # 如果该节点存在将该节点存入data数组中
            # 构造字典存放节点信息
            other_attributes = node[0]['n']
            dict = {
                'name': node_name,
                'symbolSize': 50,
                'category': '公司',
                'des': other_attributes
            }
            data.append(dict)
            # 查询与该节点有关的节点，无向，步长为1，并返回这些节点
            nodes = graph.run('MATCH (n {名称:"' + node_name + '"}) -[r]- (m) return distinct m')
            # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
            reps = graph.run('MATCH(n {名称:"' + node_name + '"})-[rel]-() return rel').data()
            # 处理节点信息
            for n in nodes:
                # 将节点信息的格式转化为json
                node = json.dumps(n.data(), ensure_ascii=False)
                node = json.loads(node)
                # 取出节点信息中person的name
                name = str(node['m']['名称'])
                other_attributes = node['m']
                labels = n[0].labels
                label = next(iter(labels))
                label = label.replace(':', '')

                # 构造字典存放单个节点信息
                dict = {
                    'name': name,
                    'symbolSize': 50,
                    'category': label,
                    'des': other_attributes
                }
                # 将单个节点信息存储进data数组中
                data.append(dict)
                # 处理relationship
            for r in reps:
                source = str(r['rel'].start_node['名称'])
                target = str(r['rel'].end_node['名称'])
                name = str(type(r['rel']).__name__)
                des = ''
                if name == '任职':
                    des = r['rel']['职位']
                elif name == '属于':
                    des = r['rel']['级别']
                elif name == '成分':
                    des = r['rel']['排名']
                elif name == '投资':
                    des = r['rel']['占总股本比例']

                dict = {
                    'source': source,
                    'target': target,
                    'name': name,
                    'des': des
                }
                links.append(dict)
            # 构造字典存储data和links
            search_data = {
                'data': data,
                'links': links
            }
            # 将dict转化为json格式
            company_neo4j_data = json.dumps(search_data)
            request.session['company_neo4j_data'] = company_neo4j_data
            # 将 ctx 数据放入会话中，根据实际情况进行处理
            request.session['ctx'] = ctx
        else:
            ctx = {'title': '数据库中暂未添加该实体'}
            print("查无实体")
    else:
        company_neo4j_data = request.session.pop('company_neo4j_data', None)
        ctx = request.session.pop('ctx', None)
    return render(request, 'company.html',
                  {'company_neo4j_data': company_neo4j_data, 'ctx': ctx, 'company_data': company_data})


def concept(request):
    # 总概念集合
    concept = []
    count = []
    concept_name = []

    if request.method == "POST":
        node_name = request.POST.get('company_name')
        nodes = graph.run('MATCH(n:`公司`{名称:"' + node_name + '"}) -[rel:`涉及`]- (m:`概念`) return m')

        for n in nodes:
            # 将节点信息的格式转化为json
            node = json.dumps(n.data(), ensure_ascii=False)
            node = json.loads(node)
            # 取出节点信息中person的name
            name = str(node['m']['名称'])
            concept_name.append(name)

    concept_nodes = graph.run('MATCH (n:`概念`) RETURN n')
    for n in concept_nodes:
        nodesStr = json.dumps(n, ensure_ascii=False)
        # 取出节点的name
        nodesList = json.loads(nodesStr)
        node_name = nodesList[0]['名称']
        concept.append(node_name)
        links_count = graph.run(
            'MATCH(n:`概念`{名称:"' + node_name + '"}) -[rel]- (m:`公司`) return COUNT(rel)').data()
        num = links_count[0]['COUNT(rel)']
        count.append(num)
    bar_data = {
        'concept': concept,
        'count': count
    }
    concept_neo4j_data = 0
    # 定义data数组，存放节点信息
    concept_data = []
    # 定义关系数组，存放节点间的关系
    concept_links = []
    # 查询所有节点，并将节点信息取出存放在data数组中
    # 执行Cypher查询
    # query = 'MATCH (n:`概念`) RETURN n LIMIT 3'
    # result = graph.run(query)
    my_list = range(0, len(concept))
    my_sample = random.sample(my_list, 3)
    for i in my_sample:
        # nodesStr = json.dumps(n, ensure_ascii=False)
        # # 取出节点的name
        # nodesList = json.loads(nodesStr)
        # node_name = nodesList[0]['名称']
        node_name = concept[i]
        # 构造字典，存储单个节点信息
        dict = {
            'name': node_name,
            'symbolSize': 50,
            'category': '概念',
            'des': {}
        }
        concept_data.append(dict)
        nodes = graph.run('MATCH(n:`概念`{名称:"' + node_name + '"}) -[]-(m:`公司`) return m').data()
        # 查询该节点所涉及的所有relationship，无向，步长为1，并返回这些relationship
        reps = graph.run('MATCH(n:`概念`{名称:"' + node_name + '"}) -[rel]- (m:`公司`) return rel').data()
        # 处理节点信息
        for n in nodes:
            # 将节点信息的格式转化为json
            node = json.dumps(n, ensure_ascii=False)
            node = json.loads(node)
            # 取出节点信息中person的name
            name = str(node['m']['名称'])
            other_attributes = node['m']
            # 构造字典存放单个节点信息
            node_dict = {
                'name': name,
                'symbolSize': 50,
                'category': '公司',
                'des': other_attributes
            }
            # 将单个节点信息存储进data数组中
            if node_dict not in concept_data:
                concept_data.append(node_dict)
        # 处理relationship
        for r in reps:
            source = str(r['rel'].start_node['名称'])
            target = str(r['rel'].end_node['名称'])
            name = str(type(r['rel']).__name__)
            link_dict = {
                'source': source,
                'target': target,
                'name': name
            }
            concept_links.append(link_dict)
            neo4j_data = {
                'data': concept_data,
                'links': concept_links
            }
            concept_neo4j_data = json.dumps(neo4j_data)

    return render(request, 'concept.html',
                  {'concept_neo4j_data': concept_neo4j_data, 'bar_data': bar_data, 'concept': concept,
                   'concept_name': concept_name})


def stock_crawl(request):
    print("crawl")
    body = json.loads(request.body.decode('utf-8'))
    # 这里调用模型或API来获取问题的回答
    code = body['stockCode']
    headers = {
        "Referer": "http://stockpage.10jqka.com.cn/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
    }
    url = "https://d.10jqka.com.cn/v2/realhead/hs_" + code + "/last.js"
    res = requests.get(url, headers=headers)
    res.encoding = 'utf-8'
    res = json.loads(res.text.split('(')[1].split(')')[0])
    print(res)
    return JsonResponse({'response': res})
